package shoot;

import com.sun.source.tree.TryTree;

import javax.imageio.ImageIO;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.channels.NonReadableChannelException;
import java.util.Random;

/**
 * 飞行物公共类
 */
public abstract class FlyingObject {
    protected int width;
    protected int height;
    protected int x;
    protected int y;

    public static final int LIFE=0;
    public static final int REMOVE=1;
    public static final int DIE=2;
    public int state=LIFE;
    
    /**
     * 构造方法
     */
    public FlyingObject(int width,int height){
        this.width=width;
        this.height=height;
        Random random=new Random();
        this.x=random.nextInt(World.WIDTH-this.width);
        this.y=-this.height;
    }

    public FlyingObject(int width,int height,int x,int y){
        this.width=width;
        this.height=height;
        this.x=x;
        this.y=y;
    }

    /**
     * 加载图片,一般图片、音频、视频 处理成静态资源
     * @return
     */
    public static BufferedImage loadImage(String filename){
        try {
			BufferedImage img=ImageIO.read(FlyingObject.class.getResource(filename));
			return img;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new RuntimeException();
		}
    }

    /**
     * 获取不同情况下的图片
     * @return
     */
    public abstract BufferedImage getImage();

    /**
     * 根据不同情况下返回的图片，画出来
     */
    public void paintObject(Graphics g){
        g.drawImage(getImage(),this.x, this.y,null);
    }

    public boolean isLife() {
    	return state==LIFE;
    }
    
    public boolean isRemove() {
    	return state==REMOVE;
    }
    public boolean isDie() {
    	return state==DIE;
    }
    
    /**
     * 飞行物移动
     */
    public abstract void step();
    
    /**
     * 判断是否越界
     * @return
     */
    public boolean goOut() {
		return this.y>World.HEIGHT;
	}

    /**
     * 碰撞
     * @return
     */
    public boolean hit(FlyingObject other) {
		int x1=this.x-other.width;
		int y1=this.y-other.height;
		int x2=this.x+this.width;
		int y2=this.y+this.height;
		
		int x=other.x;
		int y=other.y;
		//在范围内就发生碰撞
		return x>x1 && x<x2 && y>y1 && y<y2;
	}
    
    
    public void goDie() {
		state=DIE;	
    }
    

}
